<template>
  <el-container direction="vertical" class="vertical">
    <el-main class="el-main">
      <div>
        <el-form size="default" :inline="true" class="tm">
          <el-form-item>
            <el-select-v2 :style="{ width: '180px' }" v-model="userids" :options="getusers" filterable></el-select-v2>
          </el-form-item>
          <el-form-item label="题目ID">
            <el-input v-model.number="questionid" placeholder="请输入题单ID"></el-input>
          </el-form-item>
          <el-form-item label="题单ID">
            <el-input v-model.number="questionbankid" placeholder="请输入题单ID"></el-input>
          </el-form-item>
          <el-form-item class="text-right">
            <el-button type="primary" @click="start">查询</el-button>
            <el-button type="primary" v-if="Number(data?.grade) > 1" @click="() => download()">下载</el-button>
            <el-button type="primary" v-if="Number(data?.grade) > 1" @click="() => download(true)">下载全部</el-button>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="总条数:">{{ count1 }} &nbsp;（不含非代码题）&nbsp;&nbsp;</el-form-item>
            </el-col>
            <el-col :span="12" class="text-right">
              <!-- <el-form-item class="core">
                <router-link v-slot="{ href }" :custom="true" :to="{ name: 'logs', query: { teamid: data.ID } }">
                  <a class="core" v-show="isAdmin" :href="href" target="_bank">查看成员行为数据</a>
                </router-link>
              </el-form-item> -->
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="data2div" v-if="count1">
        <el-table class="data2table" :row-class-name="tableRowClassName" :data="userquestion" style="width: 100%">
          <el-table-column prop="user.name" label="用户" width="100">
            <template #default="scope">
              <router-link v-slot="{ href }" custom :to="{
          name: '用户',
          query: { userid: scope.row.userid },
        }">
                <el-link target="_blank" :href="href">{{ scope.row.user.name }}
                </el-link>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="questionid" label="题目ID" width="70">
            <template #default="scope">
              <router-link v-slot="{ href }" custom :to="{
          name: '题目',
          params: { ID: scope.row.questionid },
        }">
                <el-link target="_blank" :href="href">{{ scope.row.questionid }}
                </el-link>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="questionbankid" label="题单ID" width="70">

          </el-table-column>
          <el-table-column prop="createdAt" label="答题时间" :formatter="({ createdAt }) => TimeYH1(createdAt)" width="100">
          </el-table-column>
          <el-table-column prop="question.name" label="题目">
            <template #default="scope">
              <div :title="scope.row.question.name" class="questionname">
                <router-link v-slot="{ href }" custom :to="{
          name: '题目',
          params: { ID: scope.row.questionid },
        }">
                  <el-link target="_blank" :href="href">{{
          scope.row.question.name
        }}
                  </el-link>
                </router-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="72"></el-table-column>
          <el-table-column prop="resultdata" label="AC" width="123">
            <template #default="{ row }">
              <div v-if="row.type === '代码'">
                <span v-text="ALLTYPE[row.resultdata ? row.resultdata : 'WT'][1]"
                  :class="ALLTYPE[row.resultdata ? row.resultdata : 'WT'][1]"></span>
              </div>
              <div v-else>{{ row.resultdata ? row.resultdata : '错误' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="测试点" width="200">
            <template #default="scope">
              <div v-if="Array.isArray(scope.row.resultdataarr)">
                <span :style="{ width: '50px', display: 'inline-block' }"
                  v-for="(v, key) in acgroup(scope.row.resultdataarr)" :key="'a_' + key">
                  <span :class="ALLTYPE[v[0]][1]">{{ v[0] }}</span>
                  <span>:{{ v[1] }}</span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="result" v-if="iscode" label="其他信息" width="172">
            <template #default="scope">
              <span class="cu" v-show="scope.row.type == '代码'" @click="download2(scope.row)">
                查看源码</span>
              &nbsp;
              <span class="cu" v-show="scope.row.type == '代码'" @click="down(scope.row)">下载源码</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <el-footer class="text-right pt-2 pl-3" v-if="count1">
      <el-pagination :page-size="limit" :total="count1" @current-change="change" layout="prev, pager, next"
        :current-page="Math.floor(offset / limit) + 1"></el-pagination>
    </el-footer>
    <el-empty v-if="!count1" image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png" />

  </el-container>
</template>


<script setup lang="ts">
import { ElMessage } from "element-plus";
import moment from "moment";
import { countBy, once, pairs } from "underscore";
import { computed, inject, onMounted, onUnmounted, ref, watch } from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncselectuserquestion, Iobj } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { download2 } from "../../../util/code";
import { getExceltodownload } from "../../../util/excel";
import { ALLTYPE } from "@/util/jianchatime";
import { TimeYH, TimeYH1 } from "../../../util/time";
const prop = defineProps<{ formdata: { teamid?: number, userid?: number, formdate: Date, todate: Date }, teamusers: Studycodemodel.Iteamuser[], data: Studycodemodel.Iteam, isAdmin?: number }>()

const iscode = computed(() => {
  if (!prop.data.iscode) {
    return true
  } else {
    if (prop.isAdmin) {
      return true
    }
  }
  return false
})
const userquestion = ref<Studycodemodel.Iuserquestion[]>([]);
const route = useRoute();
const router = useRouter();
const roue = computed(() => {
  return route.query;
});
const count1 = ref(0);
const order = computed(() => {
  return roue.value.order || "ID";
});
const isAdmin = computed(() => {
  if (!user.value) return false;
  const team = getteam.value.find((e) => e.ID === teamid.value);
  if (team?.userid === user.value.ID) return 1;
  const a = team?.teamuser?.find((v) => v.userid === user.value?.ID);
  if (a) {
    return a.isAdmin;
  }
  if (user.value.remarks === "销售助教") return 2;
  return false;
});
const store = useStore(Storekey);
const getteam = computed<Studycodemodel.Iteam[]>(() => {
  return store.getters.getteam;
});



function acgroup(data?: Array<keyof Studycodemodel.IALLTYPE>) {
  if (Array.isArray(data)) {
    const c = countBy(data, (a) => {
      return a
    })
    return pairs(c)
  }
  return []
}




const getusers = computed(() => {
  return [{ value: 0, label: '全部成员' }, ...prop.teamusers.map(e => { return { value: e.user?.ID, label: e.user?.name } })]
})
const headnavdialogVisible = inject("headnavdialogVisible", () => { });
const user = computed(() => {
  return store.state.user;
});
const times = computed(() => [prop.formdata.formdate, prop.formdata.todate]);
const height = ref(window.innerHeight - 74);
function onresize(e: UIEvent) {
  height.value = window.innerHeight - 74;
}
window.onresize = onresize;

const offset = computed(() => {
  return Number(roue.value.offset) || 0;
});
const isad = computed(() => {
  return Number(roue.value.isad) || 0;
});
const limit = computed(() => {
  return Number(roue.value.limit) || 20;
});
const questionid = ref<number | null>();
const teamid = computed(() => {
  return prop.formdata.teamid
});
const userids = ref<number>(0);

onUnmounted(() => {
  window.onresize = () => { };
});

onBeforeRouteUpdate(() => {
  questionid.value = Number(roue.value.questionid) || null;

  questionbankid.value =
    (roue.value.questionbankid as unknown as number) || undefined;
});

watch(
  () => route.query,
  () => {
    start();
  }
);

const ID = ref<number[]>([])

watch(() => prop.teamusers, () => {
  start()
})

onMounted(() => {
  questionid.value = Number(roue.value.questionid) || null;
  questionbankid.value =
    Number(roue.value.questionbankid as unknown as number) || undefined;
  if (route.query.userid) {
    const isusers = getusers.value.map(e => e.value).includes(Number(route.query.userid));
    if (isusers) {
      userids.value = Number(route.query.userid);
    }
  }
  if (route.query.userquestionid) {
    ID.value = String(route.query.userquestionid).split(',').map(e => Number(e))
  }
  start()
})

const questionbankid = ref<number>();
function tableRowClassName({ row, rowIndex }: any) {
  if (rowIndex % 2 === 1) {
    return "warning-row";
  } else {
    return "success-row";
  }
}
async function start() {
  if (!user.value) {
    headnavdialogVisible();
    return;
  }
  if (
    !isad.value &&
    [questionid.value, questionbankid.value, teamid.value].filter((e) => e)
      .length === 0
  ) {
    ElMessage.error("请最少添加一种");
    return;
  }

  const userid = userids.value;
  const formquery: Iobj<Studycodemodel.Iuserquestion> = {
    _limit: limit.value,
    _offset: offset.value,
    // type: '代码',
    _order: 'ID',
    _sortable: 'DESC'
  };
  if (userid) {
    formquery.userid = userid;
  } else {
    formquery.userid = getusers.value.map(e => e.value).filter(e => e)
  }
  if (ID.value.length) {
    formquery.ID = ID.value
  }
  if (times.value) {
    formquery.createdAt = {
      lt: times.value[1],
      gt: times.value[0],
    };
  }
  if (questionbankid.value) {
    formquery.questionbankid = questionbankid.value;
  }
  if (questionid.value) {
    Object.assign(formquery, {
      questionid: questionid.value,
    });
  }
  const { rows, count } = await asyncselectuserquestion(
    Object.assign(formquery)
  );
  count1.value = count;
  userquestion.value = rows
}


function change(r: number) {
  router.push({
    query: {
      limit: limit.value,
      order: order.value,
      offset: (r - 1) * limit.value,
      questionid: questionid.value,
      questionbankid: questionbankid.value,
    },
  });
}
const onc = once(start);

function down(row: Studycodemodel.Iuserquestion) {
  const { context, language } = row;
  if (context) {
    let t = ".cpp";
    if ("c" === language) {
      t = ".c";
    }
    if ("python" === language) {
      t = ".py";
    }
    const bo = new File(
      [context],
      row.user?.name + "_" + row.question?.name + t,
      {
        type: "text/plain",
      }
    );
    var a = document.createElement("a");
    a.download = row.user?.name + "_" + row.question?.name + t;
    a.href = URL.createObjectURL(bo);
    a.click();
  } else {
    ElMessage.error("代码为空");
  }
}


async function download(b?: boolean) {
  const data1: string[][] = [
    ["用户", "题目ID", "题单ID", "答题时间", "题目名称", "AC", "代码"],
  ];
  if (!b) {
    userquestion.value.forEach((e) => {
      let {
        user,
        question,
        questionbankid,
        questionid,
        info,
        context,
        createdAt,
      } = e;
      const contextarr = []
      for (let v = 0; v < String(context).length; v = v + 30000) {
        if (v === 0 && String(context).length > 30000) {
          contextarr.push('本次提交代码过长超出Excel单元格限制，请拼接后续单元格组成代码')
        }
        contextarr.push(String(context).slice(v, v + 30000))
      }
      data1.push([
        String(user?.name),
        String(questionid),
        String(questionbankid),
        TimeYH(createdAt),
        String(question?.name),
        e.resultdata ? e.resultdata : '',
        ...contextarr,
      ]);
    });
  } else {
    const userid = userids.value;
    const formquery: Iobj<Studycodemodel.Iuserquestion> = {
      _limit: count1.value,
      _offset: 0,
      _order: 'ID',
      _sortable: 'DESC'
    };
    if (userid) {
      formquery.userid = userid;
    } else {
      formquery.userid = getusers.value.map(e => e.value).filter(e => e)
    }
    if (times.value) {
      formquery.createdAt = {
        lt: times.value[1],
        gt: times.value[0],
      };
    }
    if (questionbankid.value) {
      formquery.questionbankid = questionbankid.value;
    }
    if (questionid.value) {
      Object.assign(formquery, {
        questionid: questionid.value,
      });
    }
    const { rows, count } = await asyncselectuserquestion(
      Object.assign(formquery)
    );
    rows
      .forEach((e) => {
        let {
          user,
          question,
          questionbankid,
          questionid,
          info,
          context,
          createdAt,
        } = e;
        let { result } = e;
        const contextarr = []
        for (let v = 0; v < String(context).length; v = v + 30000) {
          if (v === 0 && String(context).length > 30000) {
            contextarr.push('本次提交代码过长超出Excel单元格限制，请拼接后续单元格组成代码')
          }
          contextarr.push(String(context).slice(v, v + 30000))
        }
        data1.push([
          String(user?.name),
          String(questionid),
          String(questionbankid),
          TimeYH(createdAt),
          String(question?.name),
          e.resultdata ? e.resultdata : '',
          ...contextarr,
        ]);
      });
  }
  if (data1.length > 1) {
    const team = getteam.value.find((e) => e.ID === teamid.value);
    const name = `${team?.name ? team.name : "学生日志"}_${moment(
      times.value[0]
    ).format("YYYYMMDD")}-${moment(times.value[1]).format("YYYYMMDD")}`;
    getExceltodownload(data1, name);
  }
}
</script>

<style scoped>
.data2table {
  --el-table-border: #fff;
  --el-table-header-text-color: var(--color-43);
  --el-table-text-color: var(--color-43);
}


.el-main {
  border: 1px solid #d9d9d9;
  box-sizing: border-box;
  /* Depth 4 */

  box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
    0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
  border-radius: 4px;
  background: #ffffff;
}

.core {
  text-align: right;
}

.core a {
  color: #666;
  text-decoration: none;
}

.core a:hover {
  color: #000;
}

.questionname {
  width: 93%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

<style>
.data2table .cell {
  padding-left: 2px !important;
  padding-right: 2px !important;
}

.data2table .el-table__cell {
  padding-top: 6px !important;
  padding-bottom: 6px !important;
}

.data2table th.is-leaf.el-table__cell {
  border-bottom: 1px solid var(--color-c4) !important;
}
</style>